package cn.tedu.boot61.controller;

import cn.tedu.boot61.mapper.WeiboMapper;
import cn.tedu.boot61.vo.User;
import cn.tedu.boot61.vo.Weibo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class WeiboController {
    @Autowired(required = false)
    WeiboMapper mapper;

    @RequestMapping("/weibo/insert")
    public int insert(Weibo weibo, MultipartFile picFile, HttpSession session) throws IOException {
        //得到当前登录的用户对象
        User u = (User) session.getAttribute("u");
        if (u==null){ //代表未登录
            return 2;//登录失败 请先登录
        }
        //得到原始文件名
        String fileName = picFile.getOriginalFilename();
        //截取后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID()+suffix;
        String dirPath = "f:/upload/";
        File dirFile = new File(dirPath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        String filepath = dirPath+fileName;
        //保存文件到filepath,
        picFile.transferTo(new File(filepath));

        //,author,url,created,user_id;
        weibo.setAuthor(u.getNick());
        weibo.setUrl("/"+fileName);
        weibo.setCreated(new Date()); //new Date得到的是当前系统时间
        weibo.setUserId(u.getId());
        mapper.insert(weibo);

        return 1; //发布成功!
    }

    @RequestMapping("/weibo/select")
    public List<Weibo> select(){
        return mapper.select();
    }
    @RequestMapping("/weibo/selectMyself")
    public List<Weibo> selectMyself(HttpSession session){
        User u = (User) session.getAttribute("u");
        if (u==null){
            return new ArrayList<>();
        }
        //通过当前登录用户的id查询所有微博
        return mapper.selectByUserId(u.getId());
    }

    @RequestMapping("/weibo/delete")
    public void deleteMyself(int id){
        mapper.delete(id);
    }

    @RequestMapping("/weibo/selectById")
    public Weibo selectById(int id){
        return mapper.selectById(id);
    }
}
